package com.example.demo.controller.usercontroller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.demo.common.ErrorCode;

import com.example.demo.common.Result;
import com.example.demo.context.UserContext;
import com.example.demo.entity.Post;
import com.example.demo.service.PostService;
import com.example.demo.service.PostLikeService;
import com.example.demo.vo.PostVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user/community/posts")
public class PostController {

    @Autowired
    private PostService postService;

    @Autowired
    private PostLikeService postLikeService;

    @GetMapping
    public Result<IPage<PostVO>> getPostList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String type) {
        return Result.success(postService.getPostList(page, size,type));
    }

    @GetMapping("/{id}")
    public Result<PostVO> getPostDetail(@PathVariable Long id) {
        postService.incrementViewCount(id);
        return Result.success(postService.getPostDetail(id));
    }

    @PostMapping
    public Result<Void> createPost(@RequestBody Post post) {
        Long userId = UserContext.getUserId();
        post.setUserId(userId);
        postService.createPost(post);
        return Result.success();
    }

    @PutMapping("/{id}")
    public Result<Void> updatePost(@PathVariable Long id, @RequestBody Post post) {
        Long userId = UserContext.getUserId();
        Post existingPost = postService.getById(id);
        if (existingPost == null || !existingPost.getUserId().equals(userId)) {
            return Result.error(ErrorCode.SYSTEM_ERROR);
        }
        post.setId(id);
        post.setUserId(userId);
        postService.updatePost(post);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<Void> deletePost(@PathVariable Long id) {
        Long userId = UserContext.getUserId();
        Post existingPost = postService.getById(id);
        if (existingPost == null || !existingPost.getUserId().equals(userId)) {
            return Result.error(ErrorCode.SYSTEM_ERROR);
        }
        postService.deletePost(id);
        return Result.success();
    }

    /**
     * 点赞帖子
     */
    @PostMapping("/{id}/like")
    public Result<Boolean> likePost(@PathVariable Long id) {
        return Result.success(postLikeService.likePost(id, UserContext.getUserId()));
    }

    /**
     * 取消点赞
     */
    @PostMapping("/{id}/unlike")
    public Result<Boolean> unlikePost(@PathVariable Long id) {
        return Result.success(postLikeService.unlikePost(id, UserContext.getUserId()));
    }
} 